package firstspark

import java.security.MessageDigest

import org.apache.commons.codec.binary.Hex
import org.apache.commons.validator.routines.checkdigit
import org.apache.spark.{SparkConf, SparkContext}

import scala.collection.mutable.ArrayBuffer

/**
  *
  * @author tzp
  * @since 2019/8/27
  */
object ImeiCreator {
  def main(args: Array[String]): Unit = {
    var prefix = "86755003"

    val conf = new SparkConf().setAppName("topn")
    val sc = new SparkContext(conf)
    val data = 0 to 9
    val ten = sc.parallelize(data)

    var imei = ten.flatMap(f => {
      generateTenBillionImei(prefix + f, 5)
    })
    imei.saveAsTextFile("/user/mz_supertool/test/tzp/xunji/imeigenerator/1")
  }

  def generateTenBillionImei(prefix: String, len: Int): ArrayBuffer[String] = {
    val fmt = "%0" + len + "d"
    val max = ("9" * len).toInt
    var arr = new ArrayBuffer[String](Math.pow(10, len).toInt)
    for (x <- 0 to max) {
      var result = prefix + fmt.format(x)
      result += checkdigit.LuhnCheckDigit.LUHN_CHECK_DIGIT.calculate(result)
      println(result)
      result = md5hex(result)
      arr += result
    }
    arr
  }

  def md5hex(input: String): String = {
    val md = MessageDigest.getInstance("MD5")
    val bt = md.digest(input.getBytes)
    Hex.encodeHexString(bt).toUpperCase()
  }
}
